<template>
  <view class="package-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">我的包裹</text>
      <text class="page-subtitle">管理您的快递取件信息</text>
    </view>

    <!-- 短信自动识别引导卡片 -->
    <view class="sms-guide-card" v-if="showSmsGuide" @click="navigateToSmsGuide">
      <view class="guide-left">
        <text class="guide-icon">📱</text>
        <view class="guide-content">
          <text class="guide-title">开启短信自动识别</text>
          <text class="guide-desc">收到快递短信自动提取取件码</text>
        </view>
      </view>
      <view class="guide-right">
        <text class="guide-arrow">→</text>
      </view>
      <view class="close-btn" @click.stop="closeSmsGuide">
        <text class="close-icon">×</text>
      </view>
    </view>

    <!-- 包裹列表 -->
    <view class="package-list" v-if="packageList.length > 0">
      <view
        class="package-item"
        v-for="(item, index) in packageList"
        :key="item.id"
        :class="{'completed': item.isDelivered}"
      >
        <view class="package-info">
          <view class="info-row">
            <text class="label">快递单号：</text>
            <text class="pickup-code">{{ item.trackingNumber }}</text>
          </view>
          <view class="info-row" v-if="item.expressCompanyName">
            <text class="label">快递公司：</text>
            <text class="location">{{ item.expressCompanyName }}</text>
          </view>
          <view class="info-row" v-if="item.description">
            <text class="label">备注：</text>
            <text class="location">{{ item.description }}</text>
          </view>
          <view class="info-row">
            <text class="label">创建时间：</text>
            <text class="time">{{ formatTime(item.createTime) }}</text>
          </view>
        </view>

        <view class="package-actions">
          <view
            class="status-badge"
            :class="{'status-pending': !item.isDelivered, 'status-completed': item.isDelivered}"
          >
            <text class="status-text">{{ item.status }}</text>
          </view>
          <button
            class="action-btn"
            :class="{'btn-complete': !item.isDelivered, 'btn-delete': item.isDelivered}"
            @click="handleAction(item)"
          >
            {{ item.isDelivered ? '删除' : '标记已签收' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text class="empty-icon">📦</text>
      <text class="empty-text">暂无包裹</text>
      <text class="empty-hint">点击右下角按钮添加包裹信息</text>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-button" @click="navigateToAdd">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

<script>
import PackageService from '@/utils/package-service.js'
import SMSReaderService from '@/utils/sms-reader-service.js'
import PermissionService from '@/utils/permission-service.js'

export default {
  data() {
    return {
      packageList: [],
      showSmsGuide: false,
      smsPermissionGranted: false
    }
  },

  onLoad() {
    this.loadPackages()
    this.checkSmsGuideStatus()
  },

  onShow() {
    // 每次显示页面时重新加载数据（从添加页返回时会刷新）
    this.loadPackages()
    this.checkSmsGuideStatus()
  },

  methods: {
    // 加载包裹列表
    async loadPackages() {
      try {
        this.packageList = await PackageService.getAllPackages()
        console.log('加载包裹列表成功:', this.packageList.length)
      } catch (error) {
        console.error('加载包裹列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 处理操作（标记已取或删除）
    handleAction(item) {
      if (item.status === '待取') {
        // 标记为已取
        this.markAsCompleted(item)
      } else {
        // 删除包裹
        this.deletePackage(item)
      }
    },

    // 标记为已取
    async markAsCompleted(item) {
      uni.showModal({
        title: '确认操作',
        content: '确认已取到该包裹？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await PackageService.updatePackageStatus(item.id, '已签收', '包裹已签收')
              await this.loadPackages()
              uni.showToast({
                title: '已标记为已签收',
                icon: 'success'
              })
            } catch (error) {
              console.error('更新包裹状态失败:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    // 删除包裹
    async deletePackage(item) {
      uni.showModal({
        title: '确认删除',
        content: '确认删除该包裹记录？',
        confirmColor: '#ff4d4f',
        success: async (res) => {
          if (res.confirm) {
            try {
              await PackageService.deletePackage(item.id)
              await this.loadPackages()
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } catch (error) {
              console.error('删除包裹失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    // 导航到添加页面
    navigateToAdd() {
      uni.navigateTo({
        url: '/pages/package/add/add'
      })
    },

    // 检查是否显示短信引导卡片
    async checkSmsGuideStatus() {
      try {
        // #ifdef APP-PLUS
        // 检查短信权限
        this.smsPermissionGranted = await SMSReaderService.checkPermission()
        
        const smsPermissionSkipped = uni.getStorageSync('sms_permission_skipped')
        const guideCardClosed = uni.getStorageSync('sms_guide_card_closed')

        // 如果未授权、未跳过、且未关闭卡片，则显示引导
        if (!this.smsPermissionGranted && !smsPermissionSkipped && !guideCardClosed) {
          this.showSmsGuide = true
        }
        // #endif
      } catch (error) {
        console.error('检查短信引导状态失败:', error)
      }
    },

    // 导航到短信引导页
    navigateToSmsGuide() {
      uni.navigateTo({
        url: '/pages/package/sms-guide/sms-guide'
      })
    },

    // 关闭短信引导卡片
    closeSmsGuide() {
      this.showSmsGuide = false
      uni.setStorageSync('sms_guide_card_closed', 'true')
      uni.showToast({
        title: '已关闭',
        icon: 'none',
        duration: 1500
      })
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
/* 主容器 */
.package-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f7f8fc 0%, #eef1f7 100%);
  padding: 20rpx;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

/* 页面标题 */
.page-header {
  text-align: center;
  padding: 40rpx 0;
}

/* 短信引导卡片 */
.sms-guide-card {
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 0 10rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
  overflow: hidden;
}

.sms-guide-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20rpx;
  width: 200rpx;
  height: 200rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.guide-left {
  display: flex;
  align-items: center;
  flex: 1;
  z-index: 1;
}

.guide-icon {
  font-size: 56rpx;
  margin-right: 20rpx;
}

.guide-content {
  display: flex;
  flex-direction: column;
}

.guide-title {
  font-size: 28rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 8rpx;
}

.guide-desc {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.9);
}

.guide-right {
  z-index: 1;
}

.guide-arrow {
  font-size: 40rpx;
  color: white;
  font-weight: bold;
}

.close-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.close-icon {
  font-size: 40rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 300;
}

.page-title {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  font-size: 24rpx;
  color: #9ca3af;
  display: block;
}

/* 包裹列表 */
.package-list {
  padding: 0 10rpx;
}

.package-item {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.package-item:active {
  transform: scale(0.98);
}

.package-item.completed {
  opacity: 0.7;
  background: #f5f5f5;
}

.package-info {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 26rpx;
  color: #6b7280;
  min-width: 140rpx;
}

.pickup-code {
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  letter-spacing: 2rpx;
}

.location {
  font-size: 28rpx;
  color: #1f2937;
}

.time {
  font-size: 24rpx;
  color: #9ca3af;
}

/* 包裹操作区域 */
.package-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1px solid #e5e7eb;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-pending {
  background: #fef3c7;
}

.status-pending .status-text {
  color: #f59e0b;
}

.status-completed {
  background: #d1fae5;
}

.status-completed .status-text {
  color: #10b981;
}

.action-btn {
  padding: 12rpx 32rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: none;
  color: white;
}

.btn-complete {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.btn-delete {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #6b7280;
  margin-bottom: 16rpx;
}

.empty-hint {
  font-size: 24rpx;
  color: #9ca3af;
}

/* 悬浮按钮 */
.fab-button {
  position: fixed;
  right: 40rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  transition: all 0.3s ease;
}

.fab-button:active {
  transform: scale(0.9);
}

.fab-icon {
  font-size: 56rpx;
  color: white;
  font-weight: 300;
}
</style>
